package com.cn.jwt.zy.jwt.filter;

import com.cn.jwt.zy.jwt.config.JwtHelpr;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * 认证
 *
 * @author zhangyi
 * @date 2018/12/15 17:46
 */
public class JwtAuthentication extends BasicAuthenticationFilter{

    public JwtAuthentication(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    /**
     * 在拦截器之前执行,进行认证
     *
     * @param request
     * @param response
     * @param chain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String token = request.getHeader("Authorization");
        StringBuffer requestURL = request.getRequestURL();
        System.out.println("获取请求头中Authorization的认证信息"+token);
        //过滤登录操作
        if(StringUtils.contains(requestURL,"login")){
            String userName = null;
            String password = null;

            System.out.println("操作登录接口");
            Enumeration<String> parameterNames = request.getParameterNames();
            while(parameterNames.hasMoreElements()){
                String s = parameterNames.nextElement();
                if(StringUtils.contains(s,"userName")){
                    userName = request.getParameter(s);
                }else if(StringUtils.contains(s,"password")){
                    password = request.getParameter(s);
                }
            }
            System.out.println("生成token....");
            //生成token
            String userToken = JwtHelpr.createJwt(userName, password, "1", 30, "123");
            ServletOutputStream outputStream = response.getOutputStream();
            String s = "生成的用户token: " + userToken;
            //写入完,需要flush
            outputStream.write(s.getBytes());
            outputStream.flush();
            chain.doFilter(request,response);
            return;
        }
//        生成的用户token:
// eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJyb2xlIjoiMSIsImV4cCI6MTU0NDg4MjEzNSwibmJmIjoxNTQ0ODgyMTM1fQ.3AFFi68R5P4UF-D0tQIbgsaTFmTAhwmdxLbS-i6AiGY
// {"timestamp":"2018-12-15T13:55:36.036+0000","status":200,"error":"OK","message":"Access is denied","path":"/loginUser"}
        /**
         * 验证token
         */
        if (token == null) {
            chain.doFilter(request, response);
            return;
        }
        //使用jwt解析token
        Claims claims = JwtHelpr.parseJwt(token, "123");
        String subject = claims.getSubject();
        SecurityContextHolder.getContext().setAuthentication(
                new UsernamePasswordAuthenticationToken(subject,null)
        );
        chain.doFilter(request,response);
    }
}
